﻿#include "JpgModule.h"



JpgModule::JpgModule()
{
	//0xffe1 0xffe0~0xffef 0xffdb 0xffc0 0xffc4 0xffdd 0xffda 0xffd9
	for (int i = 0; i < 16; i++) {
		myset.insert(0xffe0+i);
	}
	myset.insert(0xffdb);
	myset.insert(0xffc0);
	myset.insert(0xffc4);
	myset.insert(0xffdd);
	myset.insert(0xffda);
	myset.insert(0xffd9);

}


JpgModule::~JpgModule()
{
}

DWORD JpgModule::getLocation() {
	return this->location;
}
void JpgModule::setLocation(DWORD location) {
	this->location = location;
}


byte* JpgModule::getFileHead() {
	return this->fileHead;
}

int JpgModule::getFileSize() {
	return this->fileSize;
}


void JpgModule::setFileSize(int fileSize) {
	this->fileSize = fileSize;
}

bool JpgModule::parseFile(byte* buffer,int length) {
	if (length < 2) {
		return false;
	}
	int identity = buffer[2]*256+buffer[3];

	int len1 = 4;
	int len2 = 5;
	bool result = false;

	std::cout << "匹配" << std::endl;

	while ((this->myset.count(identity) || identity == 0xffd9) && len2 < (length - 1)) {
		/*result = true;
		std::cout <<std::hex<< int(buffer[len1]) ;
		std::cout <<"  "<<std::hex<< int(buffer[len2]) << std::endl;

		int thisLength= buffer[len1] * 256 + buffer[len2];

		std::cout <<std::dec<<"长度为："<< thisLength << std::endl;

		len1 += thisLength;
		len2 += thisLength;
		this->fileSize += thisLength;
		identity = buffer[len1] * 256 + buffer[len2];
		len1 += 2;
		len2 += 2;*/

		result = true;
		int thisLength = buffer[len1] * 256 + buffer[len2];

		

		len1 += thisLength;
		len2 += thisLength;
		this->fileSize += thisLength + 2;


		int nowLength = 0;
		if (identity == 0xffda) {
			identity = buffer[len1] * 256 + buffer[len2];
			//std::cout << std::hex << int(buffer[len1]);
			//std::cout << "  " << std::hex << int(buffer[len2]) << std::endl;
			len1 += 2;
			len2 += 2;
			while ((nowLength + len1 < (length - 2)) && (nowLength < 0xffff)) {
				if (buffer[nowLength + len1] == 0xff) {
					if (buffer[nowLength + len2] == 0xda) {
						this->fileSize += nowLength + 2;
						len1 += nowLength + 2;
						len2 += nowLength + 2;
					}
					else if (buffer[nowLength + len2] == 0xd9) {
						this->fileSize += nowLength;
						return result;
					}
				}
				nowLength++;
			}
		}
		else {
			identity = buffer[len1] * 256 + buffer[len2];
			//std::cout << std::hex << int(buffer[len1]);
			//std::cout << "  " << std::hex << int(buffer[len2]) << std::endl;
			len1 += 2;
			len2 += 2;
		}
	}

	return result;

}